package model

import (
	"fmt"
	"os"
	"time"

	"../config"
	"github.com/garyburd/redigo/redis"
	"github.com/jinzhu/gorm"
	"errors"
)

// DB 数据库连接
var DB *gorm.DB

// RedisPool Redis连接池
var RedisPool *redis.Pool

func initDB() {
	db, err := gorm.Open(config.DBConfig.Dialect, config.DBConfig.URL)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(-1)
	}
	if config.ServerConfig.Env == DevelopmentMode {
		db.LogMode(true)
	}
	db.DB().SetMaxIdleConns(config.DBConfig.MaxIdleConns)
	db.DB().SetMaxOpenConns(config.DBConfig.MaxOpenConns)
	DB = db
}


func initRedis() {
	RedisPool = &redis.Pool{
		MaxIdle:     config.RedisConfig.MaxIdle,
		MaxActive:   config.RedisConfig.MaxActive,
		IdleTimeout: 240 * time.Second,
		Wait:        true,
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", config.RedisConfig.URL)
			if err != nil {
				return nil, err
			}
			return c, nil
		},
	}
}

func init() {
	initDB()
	initRedis()
}
//String key, Bytes bytes, String "EX",int Cachetime
func saveRedis(key string,byte []byte,keySuffix string,cachetime int)error {
	RedisConn := RedisPool.Get()
	defer RedisConn.Close()
	//fmt.Println("args：value ", args)
	if _, redisErr := RedisConn.Do("SET", key,byte,keySuffix,cachetime); redisErr != nil {
		fmt.Println("redis set failed: ", redisErr.Error())
		return errors.New("error")
	}
	return nil
}
//String key
func delRedis(key string)error {
	RedisConn := RedisPool.Get()
	defer RedisConn.Close()
	if _, redisErr := RedisConn.Do("DEL", key); redisErr != nil {
		fmt.Println("redis set failed: ", redisErr.Error())
		return errors.New("error")
	}
	return nil
}
//String key
func getRedis(key string)([]byte, error) {
	RedisConn := RedisPool.Get()
	defer RedisConn.Close()
	userBytes, err := redis.Bytes(RedisConn.Do("GET", key))
	return userBytes, err
}